<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;

class Index extends BaseController
{
    public function index()
    {
        return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    }

    public function login() {
    $code = $this->request->post('code');
    if (empty($code)) {
        return json(['code' => 400, 'msg' => '缺少code参数']);
    }

    // 配置你的微信小程序的appid和secret
    $appid = 'wxd3adf3a5dfa16747';
    $secret = 'ae47a5f901bc2652f3efbc29d84894a4';

    // 请求微信API获取openid
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
    $response = file_get_contents($url);
    $data = json_decode($response, true);

    if (!isset($data['openid'])) {
        return json(['code' => 400, 'msg' => '获取失败']);
    }
    $openid = $data['openid'];
    $unionid = isset($data['unionid']) ? $data['unionid'] : '';
    $user = Db::name('think_user')->where('openid', $openid)->find();
    $token = md5($openid . time() . rand(1000,9999));
    if (!$user) {
        // 创建新用户
        $userId = Db::name('think_user')->insertGetId([
            'openid' => $openid,
            'unionid' => $unionid,
            'nickname' => '',
            'mobile' => '',
            'avatar' => '',
            'is_vip' => 0,
            'vip_expire_at' => null,
            'balance' => 0,
            'token'=>$token,
            'created_at' => date('Y-m-d H:i:s'),
            'last_login_at' => date('Y-m-d H:i:s')
        ]);
        $user = Db::name('think_user')->where('id', $userId)->find();
    } else {
        // 更新登录时间
        Db::name('think_user')->where('id', $user['id'])->update([
            'last_login_at' => date('Y-m-d H:i:s'),
            'token'=>$token
        ]);
    }
    return json([
        'code' => 200,
        'msg' => '登录成功',
        'data' => [
            'token' => $token
        ]
        ]);
    }

    public function hello($name = 'ThinkPHP8')
    {
        return 'hello,' . $name;
    }
}
